<template>
    <div class="app_content">
      <el-form :inline="true" ref="queryForm" :model="queryParams" class="demo-form-inline" :size="size" v-if="showSearch">
      <el-form-item label="表名称" prop="tableName">
        <el-input
          v-model="queryParams.tableName"
          placeholder="请输入表名称"
          clearable
        />
      </el-form-item>
      <el-form-item label="表描述" prop="tableComment">
        <el-input
          v-model="queryParams.tableComment"
          placeholder="请输入表描述"
          clearable
        />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button  @click="resetSubmit"><component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-redo'"/>重置</el-button>
        <el-button type="primary" @click="querySubmit"><component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-search'"/>查询</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          :size="size"
          @click="handleGenTable"
          v-hasRole="['tool:gen:code']"
        >
        <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-ad-product'"/>
        生成</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          :size="size"
          @click="openImportTable"
          v-hasRole="['tool:gen:import']"
        >
        <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-afferent'"/>
        导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          :size="size"
          :disabled="single"
          @click="handleEditTable"
          v-hasRole="['tool:gen:edit']"
        >
        <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-edit-one'"/>
        修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          :size="size"
          :disabled="multiple"
          @click="handleDelete"
          v-hasRole="['tool:gen:remove']"
        >
        <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-delete-five'"/>
        删除</el-button>
      </el-col>
      <RightToolbar :showSearch="showSearch" @queryTable='getList' @showSearchClick='showSearchClick' :columns="columns"/>
    </el-row>
    <el-table :border="$border" v-loading="loading" :data="tableData" :height="maxHeight"  style="width: 100%" @selection-change="handleSelectionChange"  :size="size"
      >
      <el-table-column type="selection" align="center" width="55"></el-table-column>
      <el-table-column label="序号" type="index" width="80" align="center" v-if="columns[0].visible">
        <template #default="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="表名称"
        align="center"
        prop="tableName"
        :show-overflow-tooltip="true"
        width="120"
        key="tableName"
        v-if="columns[1].visible"
      />
      <el-table-column
        label="表描述"
        align="center"
        prop="tableComment"
        :show-overflow-tooltip="true"
        width="120"
        key="tableComment"
        v-if="columns[2].visible"
      />
      <el-table-column
        label="实体"
        align="center"
        prop="className"
        :show-overflow-tooltip="true"
        width="120"
        key="className"
        v-if="columns[3].visible"
      />
      <el-table-column label="创建时间" align="center" prop="createTime" width="160"  key="createTime" v-if="columns[4].visible"/>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="160" key="updateTime" v-if="columns[5].visible"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            type="info"
            :size="size"
            text
            @click="handlePreview(scope.row)"
            v-hasRole="['tool:gen:preview']"
          >
          <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-preview-open'"/>
          预览</el-button>
          <el-button
            type="success"
            text
            :size="size"
            @click="handleEditTable(scope.row)"
            v-hasRole="['tool:gen:edit']"
          >
          <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-edit-one'"/>
          修改</el-button>
          <el-button
            type="danger"
            text
            :size="size"
            @click="handleDelete(scope.row)"
            v-hasRole="['tool:gen:remove']"
          >
          <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-delete-five'"/>
          删除</el-button>
          <el-button
            type="success"
            text
            :size="size"
            @click="handleSynchDb(scope.row)"
            v-hasRole="['tool:gen:edit']"
          >
          <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-reverse-operation-in'"/>
          同步</el-button>
          <el-button
            type="warning"
            text
            :size="size"
            @click="handleGenTable(scope.row)"
            v-hasRole="['tool:gen:code']"
          >
          <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-ad-product'"/>
          生成代码</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top:10px;position: absolute;right: 0;margin-right:20px">
      <el-pagination
        v-model:currentPage="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 30, 40]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
  </div>
    <!-- 预览界面 -->
    <el-drawer  v-model="preview.open"  :title="preview.title"  :direction="direction"  :show-close="true" :close-on-click-modal='false' size="70%">
      
      <el-tabs v-model="preview.activeName" tab-position="top" @tab-click="handleTabClick" style="margin-top: -30px;">
        <el-tab-pane
          v-for="(value, key) in preview.data"
          :label="key.substring(key.lastIndexOf('/')+1,key.indexOf('.vm'))"
          :name="key.substring(key.lastIndexOf('/')+1,key.indexOf('.vm'))"
          :key="key"
        >
          <el-link :underline="false" icon="el-icon-document-copy" v-clipboard:copy="value" v-clipboard:success="clipboardSuccess" style="float:right">复制</el-link>
          <pre><code class="hljs" v-html="lineNumbers(value,key.split('/')[1]) "></code></pre>
        </el-tab-pane>
      </el-tabs>
    </el-drawer>
    <el-drawer v-model="drawer" :title="drawerTitle"  :direction="direction"  :show-close="false" :close-on-click-modal='false' size="60%">
      <import-table ref="importTableRef" @ok="querySubmitOk"  @handleBack="drawer=false" />
    </el-drawer>

    <el-drawer v-model="drawer1" :title="drawerTitle1"  :destroy-on-close="true" :direction="direction1"  :show-close="false" :close-on-click-modal='false' size="90%">
      <edit-table ref="editTableRef" :tableId="tableId" :pageNum="pageNum"  @handleSuccess="handleSuccess"  @handleBack="drawer1=false" />
    </el-drawer>
    
    </div>
  </template>
  
  <script>
import RightToolbar from '@/components/RightToolbar/index.vue';
import importTable from "./importTable.vue";
import editTable from "./editTable.vue";
import hljs from 'highlight.js';
import 'highlight.js/styles/github.css';
import CompilerDom from '@/components/CompilerDom/index.vue'
import { listTable, previewTable, delTable, genCode, synchDb } from "@/api/tool/gen";
import { computed, ref ,reactive,onMounted,getCurrentInstance,toRefs,nextTick} from 'vue'
import { useStore } from 'vuex';
import { useI18n } from 'vue-i18n';
import {
Delete,
Edit,
Plus,
Switch
} from '@element-plus/icons-vue'

export default defineComponent({
  components:{
    importTable,
    RightToolbar,
    editTable,
    CompilerDom
  },
setup(){
  const { proxy } = getCurrentInstance();//关键代码
  const queryForm=ref(null)
  const formDataRef=ref(null)
  const importTableRef=ref(null)
  const { t } = useI18n();
  const store = useStore();
  const staticData=reactive({
    maxHeight: store.getters['setting/mode']=='horizontal'?document.body.clientHeight - 265:store.getters['setting/isFullScreen']!=false ?document.body.clientHeight - 360:document.body.clientHeight - 320 ,
      // 遮罩层
      loading: true,
      // 唯一标识符
      uniqueId: "",
      // 选中数组
      ids: [],
      drawer:false,
      drawerTitle:"导入表操作",
      drawer1:false,
      drawerTitle1:"",
      direction :'ltr',
      direction1 :'ltr',
      background:false,
      fullscreen:false,
      disabled :false,
      tableId:null,
      pageNum:0,
      // 选中表数组
      tableNames: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      open:false,
      tableData:[],
      // 表数据
      tableList: [],
      // 日期范围
      dateRange: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tableName: undefined,
        tableComment: undefined
      },
      // 预览参数
      preview: {
        open: false,
        title: "代码预览",
        data: {},
        activeName: "domain.java"
      },
      ExportHead:{
      
    },
    // 列信息
    columns: [
      { key: 0, label: `序号`, visible: true },
      { key: 1, label: `表名称`, visible: true },
      { key: 2, label: `表描述`, visible: true },
      { key: 3, label: `实体`, visible: true },
      { key: 4, label: `创建时间`, visible: true },
      { key: 5, label: `更新时间`, visible: true },

      
    ],
  })
  const size = computed(() => {
        return store.getters['setting/size'];
  });

  const small =computed(() => {
    return size.value=='small'?true:false
  });
  onMounted(() => {
    
    proxy.getList()
  })
  // activated() {
  //   const time = this.$route.query.t;
  //   if (time != null && time != this.uniqueId) {
  //     this.uniqueId = time;
  //     this.queryParams.pageNum = Number(this.$route.query.pageNum);
  //     this.getList();
  //   }
  // }
  const methods={
    handleTabClick(){
      let scrollEle = document.querySelector('.el-drawer__body')
          scrollEle.scrollTo({
          top: 0,
          left:0,
          behavior: 'smooth'
        });
    },
    /**
     * @param {String} content 代码内容
     * @param {String} lang 代码语言
     * @returns table标签及内容
     */
     lineNumbers (content, lang){
      
        // 验证当前语言是否存在
        const language = hljs.getLanguage(lang) ? lang : 'xml';
        // 使代码转换成带有标签的节点
        const textHtml = hljs.highlight(content, { language }).value;
        // 如果不想添加行号可以直接
        // return textHtml;
 
        // 返回分割后的数组
        const lines = proxy.getLines(textHtml);
    
        // // 自定义代码块的标签节点
        // let html = '';
        // for (var i = 0, l = lines.length; i < l; i++) {
        //     let text = lines[i].length > 0 ? lines[i] : ' '
        //     html += `<tr>
        //         <td class="blob-num" data-line-number="${i}"></td>
        //         <td class="blob-code blob-code-inner">${text}</td>
        //       </tr>`;
        // }
    
        // return `<table class="highlight">${html}</table>`;
        return textHtml;
    },
    
    // 根据换行符或回车分割成字符串数组
    getLines(text) {
        if (text.length === 0) return [];
        return text.split(/\r\n|\r|\n/g);
    },

    /** 查询表集合 */
    getList() {
      staticData.loading = true;
      listTable(proxy.$addDateRange(staticData.queryParams, staticData.dateRange)).then(response => {
        staticData.tableData = response.rows;
        staticData.total = response.total;
        staticData.loading = false;
        }
      );
    },
   
    /** 生成代码操作 */
    handleGenTable(row) {
      const tableNames = row.tableName || staticData.tableNames;
      if (tableNames == "") {
        proxy.Error("请选择要生成的数据");
        return;
      }
      if(row.genType === "1") {
        genCode(row.tableName).then(response => {
          proxy.Success("成功生成到自定义路径：" + row.genPath);
        });
      } else {
        proxy.$download("/tool/gen/batchGenCode?tables=" + tableNames,tableNames+"_vite.zip");
      }
    },
    handleSuccess(){
      staticData.drawer1=false
      
      proxy.getList()
    },
    /** 同步数据库操作 */
    handleSynchDb(row) {
      const tableName = row.tableName;
        ElMessageBox.confirm('确认要强制同步"' + tableName + '"表结构吗？', t('confirm.title'), {
          confirmButtonText: t('btn.confirm'),
          cancelButtonText: t('btn.cancel'),
          type: "warning"
        })
      .then(function() {
        return synchDb(tableName);
      }).then(() => {
        proxy.Success("同步成功");
      }).catch(() => {});
    },
    /** 打开导入表弹窗 */
    openImportTable() {
      staticData.drawer=true
    },

    /** 预览按钮 */
    handlePreview(row) {
      
      previewTable(row.tableId).then(response => {
        staticData.preview.data = response.data;
        staticData.preview.open = true;
        staticData.preview.activeName = "domain.java";
        // nextTick(() => {
        //   hljs.highlightAll();
        // })
      });
    },
    /** 高亮显示 */
    // highlightedCode(code, key) {
    //   const vmName = key.substring(key.lastIndexOf("/") + 1, key.indexOf(".vm"));
    //   var language = vmName.substring(vmName.indexOf(".") + 1, vmName.length);
    //   const result = hljs.highlight(language, code || "", true);
    //   return result.value || '&nbsp;';
    // },
    /** 复制代码成功 */
    clipboardSuccess() {
      proxy.Success("复制成功");
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      staticData.ids = selection.map(item => item.tableId);
      staticData.tableNames = selection.map(item => item.tableName);
      staticData.single = selection.length != 1;
      staticData.multiple = !selection.length;
    },
    /** 修改按钮操作 */
    handleEditTable(row) {
      staticData.tableId = row.tableId || staticData.ids[0];
      const tableName = row.tableName || staticData.tableNames[0];
      staticData.pageNum =staticData.queryParams.pageNum ;
      staticData.drawerTitle1="修改[" + tableName + "]生成配置"
      staticData.drawer1=true
      // this.$tab.openPage("修改[" + tableName + "]生成配置", '/tool/gen-edit/index/' + tableId, params);
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const tableIds = row.tableId || staticData.ids;
      const tableNames = row.tableName || staticData.tableNames;
        ElMessageBox.confirm('是否确认删除表为"' + tableNames + '"的数据项？', t('confirm.title'), {
          confirmButtonText: t('btn.confirm'),
          cancelButtonText: t('btn.cancel'),
          type: "warning"
        })
      .then(function() {
        return delTable(tableIds);
      }).then(() => {
        proxy.getList();
        proxy.Success("删除成功");
      }).catch(() => {});
    },
    /**
      * 显示或隐藏搜索条件
      **/
      showSearchClick(data){
       staticData.showSearch=data
     },
    /**关闭弹窗 */
    cancel(){
      staticData.treeis=false
      staticData.open = false;
    },
    resetSubmit(){
      staticData.dateRange=[]
      queryForm.value.resetFields();
      proxy.getList()
    },
     querySubmitOk(){

      staticData.drawer=false
       proxy.querySubmit()
    },
    querySubmit(){
      staticData.queryParams.pageNum = 1;
      proxy.getList()
    },
    handleSizeChange (val) {
      console.log(`${val} items per page`)
      staticData.queryParams.pageSize =val;
      proxy.getList()
    },
    handleCurrentChange(val){
      console.log(`current page: ${val}`)
      staticData.queryParams.pageNum =val;
      proxy.getList()
    }
   }
    return {
      Delete,
      Edit,
      Plus,
      Switch,
      size,
      small,
      queryForm,
      formDataRef,
      ...methods,
      ...toRefs(staticData)
    }
}


})

</script>
<style scoped>
.app_content{
  
  margin-top: 30px;
  margin-left: 10px;
}
.mb8{
  margin-bottom: 10px;
}
:deep(.el-tabs__header){
  position: fixed !important;
    top: 46px;
    left: 0;
    width: 69%;
    background-color: white;
    z-index: 1000;
}
:deep(.el-tabs__content){
  margin-top: 35px;
}
:deep(.el-tabs__nav){
 margin-left: 20px;
}
</style>